package com.boxing.servlet;

import com.boxing.bean.LoginResult;
import com.boxing.bean.RespContent;
import com.boxing.bean.User;
import com.boxing.bean.UserDesc;
import com.boxing.service.UserService;
import com.boxing.utils.WebUtil;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.UUID;

@WebServlet(name = "LoginServlet", value = "/LoginServlet")
public class LoginServlet extends BaseServlet{

    private  UserService userService = new UserService();

    private void getUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        boolean login = WebUtil.isLogin(request);
        RespContent<UserDesc> respContent = new RespContent<>();
        Gson gson = new Gson();
        if (login){
            // 根据name去数据库里查数据
            HttpSession session = request.getSession();
            User user = (User) session.getAttribute("token");
            String name = user.getUser();
            UserDesc userDesc = userService.getUser(name);
            if (userDesc != null){
                // 将详细信息响应给浏览器端
                respContent.setCode(20);
                respContent.setMsg("");
                respContent.setData(userDesc);
            }else {
                // t_user_desc 中没有 name 用户
                respContent.setCode(30);
                respContent.setMsg("服务器出现异常,程序员小哥哥正在抢修");
            }
        } else {
            // 没有登录
            respContent.setCode(40);
            respContent.setMsg("没有登录, 请登录后重试");
        }
        String toJson = gson.toJson(respContent);
        response.getWriter().print(toJson);
    }

    /**
     * 校验用户名是否已存在
     */
    private void verifyUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String name = request.getParameter("name");
        // 去数据库里做校验
        boolean exist = userService.existUser(name);
        RespContent respContent = new RespContent<>();
        if (exist){
            // 用户名已存在, 响应给浏览器
            respContent.setCode(10);
            respContent.setMsg("用户名已存在");
        }else {
            // 用户名不存在
            respContent.setCode(20);
            respContent.setMsg("可以注册");
        }
        response.getWriter().print(new Gson().toJson(respContent));
    }

    /**
     * 注册
     */
    private void register(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException{
        // 注 册     接受浏览器端传递的 用户名 密码 邮箱
        String name = request.getParameter("name");
        String psd = request.getParameter("psd");
        String email = request.getParameter("email");
        // 将数据保存在数据库中
        User user = new User(name, psd);
        user.setEmail(email);
        boolean register = userService.register(user);
        // 响应给浏览器端注册结果
        RespContent respContent = new RespContent<>();
        if (register){
            respContent.setCode(20);
            respContent.setMsg("注册成功");
        }else {
            respContent.setCode(30);
            respContent.setMsg("注册失败");
        }
        // 将java对象转换成json字符串
        Gson gson = new Gson();
        String jsonStr = gson.toJson(respContent);
        response.getWriter().print(jsonStr);
    }

    /**
     * 登录
     */
    private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        String name = request.getParameter("name");
        String psd = request.getParameter("psd");
        User user = new User(name, psd);
        // 去数据库里验证
        boolean loginResult = userService.login(user);
        RespContent<LoginResult> respContent = new RespContent<>();
        Gson gson = new Gson();
        if (loginResult){
            // 登录成功, 需要生成一个token
            String uuid = UUID.randomUUID().toString();

            // 把生成的token保存的session 中, 使所有的servlet共享
            HttpSession session = request.getSession(true);
            // 将 user 存储到 session 中
            user.setToken(uuid);
            session.setAttribute("token", user);
            session.setMaxInactiveInterval(1000000000);


            Cookie cookie = new Cookie("token", uuid);
            //设置cookie的有效时长
//            cookie.setMaxAge(100);
            // 设置此cookie 不能被浏览器脚本读取
            cookie.setHttpOnly(true);
            response.addCookie(cookie);
            // 跳转到登录成功的页面
            respContent.setCode(20);
            respContent.setMsg("恭喜登录成功!");
        }else {
            // 提示用户登录失败以及具体的原因
            // 用户名或者密码不正确
            respContent.setCode(30);
            respContent.setMsg("用户名或密码不正确,请重新输入!");
        }
        String toJson = gson.toJson(respContent);
        response.getWriter().print(toJson);
    }

    private void editUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        boolean login = WebUtil.isLogin(request);
        RespContent<UserDesc> respContent = new RespContent<>();
        Gson gson = new Gson();
        if (login) {
            String email = request.getParameter("email");
            String sex = request.getParameter("sex");
            // 根据name去数据库里修改数据
            HttpSession session = request.getSession();
            User user = (User) session.getAttribute("token");
            String name = user.getUser();
            UserDesc userDesc = new UserDesc();
            userDesc.setName(name);
            userDesc.setSex(sex);
            userDesc.setEmail(email);
            boolean end = userService.editUser(userDesc);
            if (end){
                respContent.setCode(20);
                respContent.setMsg("登录");
            }else {
                respContent.setCode(30);
                respContent.setMsg("用户名或密码不正确,请重新输入!");
            }
        } else {
            // 没有登录
            respContent.setCode(40);
            respContent.setMsg("没有登录, 请登录后重试");
        }
        String toJson = gson.toJson(respContent);
        response.getWriter().print(toJson);
    }
}
